//
//  ST_TIANLogPublisher.swift
//  btvideo
//
//  Created by Jason on 2022/1/21.
//  Copyright © 2022 JarvanZhang. All rights reserved.
//
import Foundation
import CocoaAsyncSocket
import SwiftyUserDefaults

class ST_TIANLogPublisher : NSObject{
    
    static let `default` = ST_TIANLogPublisher()
    
    private override init(){
        
        super.init()
        
        ST_NetworkStatusManager.shared.networkStatusObservable.subscribe(onNext: { status in
            
            if status == .reachable{
                self.connect_server()
            }
            
        }).disposed(by: rx.disposeBag)
    }
    
    private let port:UInt16 = 1338
    
    private let host = Defaults[.logIPAddress]
    
    private var socketSet = Set<GCDAsyncSocket>()
}

extension ST_TIANLogPublisher{
    
    func push(log:String){
        
        socketSet.first(where: { $0.isConnected })?.write(log.data(using: .utf8), withTimeout: -1, tag: 0)
        
    }
}


extension ST_TIANLogPublisher{
    
    private func keep_alive_handle(){
        
        if socketSet.contains(where: { $0.isConnected }){
            return
        }
        
        connect_server()
        
    }
    
    private func connect_server(){
        
        if socketSet.contains(where: { $0.isConnected }){
            return
        }
        
        let socket = GCDAsyncSocket.init(delegate: self, delegateQueue: .global())
        
        try? socket.connect(toHost: host, onPort: port)
        
        socketSet.update(with: socket)
        
    }
}


extension ST_TIANLogPublisher:GCDAsyncSocketDelegate{
    
    func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) {
        
    }
    
    
    func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) {
        
        
        DispatchQueue.main.async {
            
            self.socketSet.remove(sock)
            
            self.keep_alive_handle()
        }
    }
    
}





//MARK: - UserDefaults

extension DefaultsKeys {
    static let logIPAddress = DefaultsKey<String>("TIAN_lopIPAddress", defaultValue: "192.168.6.110")
}
